<template>
  <div class="delivery-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>配送管理</h1>
        <p class="header-desc">管理您接单的配送任务，跟踪配送进度</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 订单搜索和筛选 -->
    <OrderFilter 
      v-model:search="searchQuery"
      v-model:status="statusFilter"
      @search="handleSearch"
      @filter="handleFilter"
    />

    <!-- 订单列表 -->
    <OrderList
      :orders="filteredOrders"
      :loading="loading"
      @select-order="handleSelectOrder"
      @update-status="handleUpdateStatus"
      @refresh="refreshData"
    />

    <!-- 轨迹管理抽屉 -->
    <TrackManagementDrawer
      v-model:visible="drawerVisible"
      :selected-order="selectedOrder"
      :track-activities="currentTrackActivities"
      @add-track="handleAddTrack"
      @update-track="handleUpdateTrack"
      @delete-track="handleDeleteTrack"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import OrderFilter from './components/OrderFilter.vue'
import OrderList from './components/OrderList.vue'
import TrackManagementDrawer from './components/TrackManagementDrawer.vue'
import { courierApi, type DeliveryAssignment, type AvailableOrder } from '@/api/courier'
import { userApi } from '@/api/user'

const route = useRoute()

// 类型定义
interface Order {
  id: string
  orderNumber: string
  senderName: string
  senderPhone: string
  senderAddress: string
  senderCoords?: [number, number]
  recipientName: string
  recipientPhone: string
  recipientAddress: string
  recipientCoords?: [number, number]
  status: number
  statusText: string
  createTime: string
  updateTime: string
  courierName?: string
  estimatedDelivery?: string
  assignmentId?: number
  orderId?: number
}

interface TrackActivity {
  id?: string
  content: string
  timestamp: string
  type: string
  color: string
  location: string
  operator?: string
  remark?: string
  status: number
  coordinates?: [number, number]
}

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const statusFilter = ref<number | ''>('')
const drawerVisible = ref(false)
const selectedOrder = ref<Order | null>(null)

// 订单数据
const orders = ref<Order[]>([])
const currentTrackActivities = ref<TrackActivity[]>([])

// 计算属性
const filteredOrders = computed(() => {
  let result = orders.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(order => 
      order.orderNumber.toLowerCase().includes(query) ||
      order.senderName.toLowerCase().includes(query) ||
      order.recipientName.toLowerCase().includes(query) ||
      order.senderAddress.toLowerCase().includes(query) ||
      order.recipientAddress.toLowerCase().includes(query)
    )
  }

  // 状态过滤
  if (statusFilter.value !== '') {
    result = result.filter(order => order.status === statusFilter.value)
  }

  return result
})

// 处理路由参数
const handleRouteParams = () => {
  const { orderId, assignmentId, action, autoOpen } = route.query
  
  if (orderId && (action === 'start-delivery' || action === 'manage-track')) {
    console.log('准备处理订单，订单ID:', orderId, '配送记录ID:', assignmentId)
    // 等待订单数据加载完成后，自动选中该订单
    setTimeout(() => {
      const targetOrder = orders.value.find(order => 
        order.orderId?.toString() === orderId || 
        order.id === orderId
      )
      if (targetOrder) {
        handleSelectOrder(targetOrder)
        // 如果指定了自动打开，确保抽屉打开
        if (autoOpen === 'true') {
          drawerVisible.value = true
        }
      }
    }, 1000)
  }
}

// 监听路由参数变化
watch(() => route.query, (newQuery) => {
  if (newQuery.orderId) {
    console.log('从其他页面跳转过来，订单ID:', newQuery.orderId)
    // 如果有特定订单ID，可以在加载完成后自动选中该订单
    handleRouteParams()
  }
}, { immediate: true })

// 获取状态文本
const getStatusText = (status: number): string => {
  const statusMap: Record<number, string> = {
    0: '待揽收',
    1: '待发货',
    2: '运输中',
    3: '已送达',
    4: '已签收'
  }
  return statusMap[status] || '未知状态'
}

// 根据轨迹状态获取类型
const getTrackType = (status: number): string => {
  const typeMap: Record<number, string> = {
    1: 'info',      // 已下单
    2: 'primary',   // 待揽件
    3: 'primary',   // 已揽件
    4: 'warning',   // 运输中
    5: 'warning',   // 已到达
    6: 'success'    // 已签收
  }
  return typeMap[status] || 'info'
}

// 根据轨迹状态获取颜色
const getTrackColor = (status: number): string => {
  const colorMap: Record<number, string> = {
    1: '#909399',   // 已下单 - 灰色
    2: '#409EFF',   // 待揽件 - 蓝色
    3: '#409EFF',   // 已揽件 - 蓝色
    4: '#E6A23C',   // 运输中 - 橙色
    5: '#E6A23C',   // 已到达 - 橙色
    6: '#67C23A'    // 已签收 - 绿色
  }
  return colorMap[status] || '#909399'
}

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    await fetchOrders()
  } finally {
    loading.value = false
  }
}

const fetchOrders = async () => {
  try {
    console.log('获取配送员的接单订单')
    const response = await courierApi.getMyAssignments(1, 100) // 获取所有接单
    
    if (response.code === 200) {
      const assignments = response.data.list || []
      console.log('获取到的配送记录:', assignments)
      
      // 转换配送记录为订单格式，只显示可配送的状态(1-待发货, 2-运输中, 3-已送达)
      orders.value = assignments
        .filter((assignment: DeliveryAssignment) => [1, 2, 3].includes(assignment.status))
        .map((assignment: DeliveryAssignment) => ({
          id: assignment.assignmentId.toString(),
          orderNumber: assignment.orderNumber,
          senderName: assignment.senderName,
          senderPhone: '', // 配送记录中没有电话，需要从订单详情获取
          senderAddress: '',
          recipientName: assignment.receiverName,
          recipientPhone: '',
          recipientAddress: assignment.receiverAddress,
          status: assignment.status,
          statusText: getStatusText(assignment.status),
          createTime: assignment.assignedAt,
          updateTime: assignment.updatedAt,
          courierName: '当前配送员', // 当前登录的配送员
          estimatedDelivery: assignment.completedAt,
          assignmentId: assignment.assignmentId,
          orderId: assignment.orderId
        }))
      
      // 补充订单详细信息
      await enrichOrderDetails()
    } else {
      console.error('获取配送记录失败:', response.message)
      ElMessage.error(response.message || '获取配送记录失败')
      orders.value = []
    }
  } catch (error: any) {
    console.error('获取配送记录异常:', error)
    ElMessage.error('获取配送记录失败')
    orders.value = []
  }
}

// 补充订单详细信息
const enrichOrderDetails = async () => {
  console.log('补充订单详细信息')
  for (const order of orders.value) {
    if (order.orderId) {
      try {
        const response = await courierApi.getOrderDetails(order.orderId)
        if (response.code === 200) {
          const orderDetail: AvailableOrder = response.data
          // 更新订单信息
          order.senderPhone = orderDetail.senderPhone
          order.senderAddress = orderDetail.senderAddress
          order.recipientPhone = orderDetail.receiverPhone
          // 可以添加更多字段
        }
      } catch (error) {
        console.error(`获取订单${order.orderId}详情失败:`, error)
      }
    }
  }
}

const handleSearch = (query: string) => {
  searchQuery.value = query
}

const handleFilter = (status: number | '') => {
  statusFilter.value = status
}

const handleSelectOrder = async (order: Order) => {
  selectedOrder.value = order
  await fetchTrackActivities(order.id)
  drawerVisible.value = true
}

const fetchTrackActivities = async (orderId: string) => {
  console.log('获取订单轨迹:', orderId)
  
  // 查找对应的订单
  const order = orders.value.find(o => o.id === orderId)
  if (!order || !order.orderId) {
    currentTrackActivities.value = []
    return
  }
  
  try {
    console.log('开始获取轨迹数据，订单ID:', order.orderId)
    
    // 优先尝试使用用户API获取轨迹（与track模块保持一致）
    const response = await userApi.getTrackByOrderId(order.orderId)
    console.log('轨迹数据响应:', response)
    
    if (response.code === 200 && response.data) {
      // 将API返回的轨迹数据转换为组件需要的格式
      const trackData = response.data
      if (trackData.trackRecords && trackData.trackRecords.length > 0) {
        currentTrackActivities.value = trackData.trackRecords.map((record: any) => ({
          id: `${trackData.id}_${record.timestamp}`,
          content: record.description,
          timestamp: record.timestamp,
          type: getTrackType(record.status),
          color: getTrackColor(record.status),
          location: record.location?.address || record.location || '未知位置',
          operator: record.operator || '系统',
          remark: record.remark || '',
          status: record.status,
          coordinates: record.location?.longitude && record.location?.latitude 
            ? [record.location.longitude, record.location.latitude] as [number, number]
            : undefined
        })).reverse() // 最新的在前面
        
        console.log('轨迹数据加载成功:', currentTrackActivities.value.length, '条记录')
      } else {
        console.log('暂无轨迹记录，使用基础轨迹')
        currentTrackActivities.value = generateTrackActivities(order)
      }
    } else {
      console.warn('获取轨迹失败:', response.message)
      // 如果API返回失败，使用模拟数据作为备用
      currentTrackActivities.value = generateTrackActivities(order)
    }
  } catch (error: any) {
    console.error('获取轨迹异常:', error)
    // 如果是404错误，说明暂无轨迹数据
    if (error.code === 404) {
      console.log('暂无物流轨迹信息，使用基础轨迹')
      currentTrackActivities.value = generateTrackActivities(order)
    } else {
      console.error('获取轨迹API调用失败，使用模拟数据')
      currentTrackActivities.value = generateTrackActivities(order)
    }
  }
  }

// 根据订单状态生成轨迹活动
const generateTrackActivities = (order: Order): TrackActivity[] => {
  const activities: TrackActivity[] = []
  const baseTime = new Date(order.createTime)
  
  // 接单记录
  activities.push({
    id: '1',
    content: '配送员已接单',
    timestamp: order.createTime,
    type: 'success',
    color: '#67C23A',
    location: '配送中心',
    operator: order.courierName || '配送员',
    remark: '订单已被配送员接取',
    status: 0
  })
  
  // 根据当前状态添加后续轨迹
  if (order.status >= 1) {
    activities.push({
      id: '2',
      content: '开始发货',
      timestamp: new Date(baseTime.getTime() + 30 * 60 * 1000).toISOString(),
      type: 'primary',
      color: '#409EFF',
      location: order.senderAddress || '寄件地址',
      operator: order.courierName || '配送员',
      remark: '包裹已取件，准备运输',
      status: 1
    })
  }
  
  if (order.status >= 2) {
    activities.push({
      id: '3',
      content: '运输中',
      timestamp: new Date(baseTime.getTime() + 2 * 60 * 60 * 1000).toISOString(),
      type: 'primary',
      color: '#409EFF',
      location: '运输途中',
      operator: order.courierName || '配送员',
      remark: '包裹正在运输中',
      status: 2
    })
  }
  
  if (order.status >= 3) {
    activities.push({
      id: '4',
      content: '已送达',
      timestamp: order.updateTime,
      type: 'warning',
      color: '#E6A23C',
      location: order.recipientAddress || '收件地址',
      operator: order.courierName || '配送员',
      remark: '包裹已送达收件地址',
      status: 3
    })
  }
  
  return activities.reverse() // 最新的在前面
}

const handleUpdateStatus = async (orderId: string, newStatus: number) => {
  try {
    const order = orders.value.find(o => o.id === orderId)
    if (!order || !order.assignmentId) {
      ElMessage.error('订单信息错误')
      return
    }
    
    console.log('更新配送状态:', { assignmentId: order.assignmentId, newStatus })
    
    // 调用API更新状态
    const response = await courierApi.updateDeliveryStatus(
      order.assignmentId,
      newStatus,
      `状态更新为: ${getStatusText(newStatus)}`
    )
    
    if (response.code === 200) {
      // 更新本地状态
      order.status = newStatus
      order.statusText = getStatusText(newStatus)
      order.updateTime = new Date().toISOString()
      
      ElMessage.success('订单状态更新成功')
      
      // 如果抽屉是打开的，刷新轨迹数据
      if (drawerVisible.value && selectedOrder.value?.id === orderId) {
        await fetchTrackActivities(orderId)
      }
    } else {
      ElMessage.error(response.message || '更新状态失败')
    }
  } catch (error: any) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

const handleAddTrack = async (trackData: any) => {
  console.log('添加轨迹记录:', trackData)
  
  if (!selectedOrder.value) {
    ElMessage.error('请先选择订单')
    return
  }
  
  console.log('准备添加轨迹，订单ID:', selectedOrder.value.orderId)
  
  try {
    // 传递完整的数据，包括坐标
    await courierApi.addTrack(selectedOrder.value.orderId, {
      location: trackData.location,
      latitude: trackData.latitude,   // 传递纬度
      longitude: trackData.longitude, // 传递经度
      remark: trackData.remark,
      status: trackData.status
    })
    
    ElMessage.success('轨迹添加成功')
    drawerVisible.value = false  // 修复：使用drawerVisible而不是showTrackForm
    
    // 重新获取轨迹数据
    await fetchTrackActivities()
  } catch (error) {
    console.error('添加轨迹失败，API响应:', error)
    ElMessage.error('添加轨迹失败')
  }
}

const handleUpdateTrack = async (trackId: string, trackData: Partial<TrackActivity>) => {
  try {
    const index = currentTrackActivities.value.findIndex(t => t.id === trackId)
    if (index !== -1) {
      currentTrackActivities.value[index] = {
        ...currentTrackActivities.value[index],
        ...trackData
      }
    }
    
    ElMessage.success('轨迹记录更新成功')
  } catch (error) {
    ElMessage.error('更新轨迹记录失败')
  }
}

const handleDeleteTrack = async (trackId: string) => {
  try {
    const index = currentTrackActivities.value.findIndex(t => t.id === trackId)
    if (index !== -1) {
      currentTrackActivities.value.splice(index, 1)
    }
    
    ElMessage.success('轨迹记录删除成功')
  } catch (error) {
    ElMessage.error('删除轨迹记录失败')
  }
}

onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.delivery-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.header-content h1 {
  margin: 0 0 8px 0;
  color: #1e293b;
  font-size: 24px;
  font-weight: 600;
}

.header-desc {
  margin: 0;
  color: #64748b;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

@media (max-width: 768px) {
  .delivery-management {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>